package com.dapeis.web.wx.wx.handler;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpCustomMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.bean.outxmlbuilder.NewsBuilder;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.springframework.stereotype.Component;

import com.ag.module.common.web.TagUtils;
import com.ag.utils.DictionarySettingUtils;
import com.ag.utils.json.AGsonBuilder;
import com.dapeis.domain.User;
import com.dapeis.domain.UserThirdPartyLogin;
import com.dapeis.exception.user.UserSourceExistException;
import com.dapeis.service.UserService;
import com.dapeis.service.UserThirdPartyLoginService;

/**
 * 微信关注事件处理 Title:WxEventSubscribeHandler.java WxEventSubscribeHandler
 * Description:
 * 
 * @author yuanyong
 * @date 2017年4月18日 上午9:22:13 Email: hzyuanyong@126.com
 *
 */
@Component
public class WxEventSubscribeHandler implements WxMpMessageHandler {
    @Resource
    UserService userService;
    @Resource
    UserThirdPartyLoginService userThirdPartyLoginService;

    @Override
    public WxMpXmlOutMessage handle(final WxMpXmlMessage wxMessage,
	    Map<String, Object> context, final WxMpService wxMpService,
	    WxSessionManager sessionManager) {
	WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
	// 关注微信号后推送的信息从配置： wx_webapp.subscribe_message.* 里面取
	item.setDescription(DictionarySettingUtils
		.getParameterValueWithDefault(
			"wx_webapp.subscribe_message.description", "这是描述"));
	item.setPicUrl(DictionarySettingUtils.getParameterValueWithDefault(
		"wx_webapp.subscribe_message.picUrl",
		"http://img.dapeis.com/resources/dsp_defalut.png"));
	item.setTitle(DictionarySettingUtils.getParameterValueWithDefault(
		"wx_webapp.subscribe_message.title", "这是标题"));
	item.setUrl(DictionarySettingUtils.getParameterValueWithDefault(
		"wx_webapp.subscribe_message.url", "http://www.dapeis.com"));
	NewsBuilder newsBuilder = WxMpXmlOutMessage.NEWS().addArticle(item);
	WxMpXmlOutNewsMessage m = newsBuilder
		.fromUser(wxMessage.getToUserName())
		.toUser(wxMessage.getFromUserName()).build();
	try {
	    WxMpUser userInfo = wxMpService.userInfo(
		    wxMessage.getFromUserName(), null);
	    User user = userService.getUserByWeixinOpenId(userInfo.getOpenId());
	    if (null == user) {
		userService.registFromWeixin(userInfo.getOpenId(),
			userInfo.getNickname(), userInfo.getHeadImgUrl(),
			AGsonBuilder.create().toJson(userInfo));
	    }
	    System.out.println("userInfo:" + userInfo.toString());
	} catch (UserSourceExistException usee) {
	    System.out.println("用户已经存在，无需再次注册.");
	} catch (WxErrorException e) {
	    e.printStackTrace();
	}

	new Thread() {
	    @Override
	    public void run() {
		try {
		    Thread.sleep(2000);
		} catch (InterruptedException e1) {
		    e1.printStackTrace();
		}
		UserThirdPartyLogin userThirdPartyLogin = userThirdPartyLoginService
			.getWxUserThirdPartyLogin(wxMessage.getFromUserName());
		// User userByWeixinOpenId = userService
		// .getUserByWeixinOpenId(wxMessage.getFromUserName());
		WxMpCustomMessage gzsj = WxMpCustomMessage
			.TEXT()
			.toUser(wxMessage.getFromUserName())
			.content(
				"时间: "
					+ TagUtils.formatDate(
						userThirdPartyLogin
							.getRecordCreateTime(),
						"MM-dd HH:mm")).build();
		try {
		    wxMpService.customMessageSend(gzsj);
		} catch (WxErrorException e) {
		    e.printStackTrace();
		}
	    };
	}.start();

	return m;
    }

}
